package com.central.oauth.config;

import com.central.oauth.service.impl.RedisClientDetailsService;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * OAuth2 授权服务器配置. 3 个关键方法, 参考网址: https://blog.csdn.net/u013815546/article/details/76977239
 * <p>
 * 在类上添加 @EnableAuthorizationServer 注解，声明开启 OAuth 授权服务器的功能。 关于 spring-security 的说明请到 {@link
 * com.central.gateway.config.ResourceServerConfiguration} 类查看注释
 */
@Configuration
@EnableAuthorizationServer
@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    /**
     * 注入 authenticationManager 来支持 password grant type
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private WebResponseExceptionTranslator webResponseExceptionTranslator;

    @Autowired
    private RedisClientDetailsService clientDetailsService;

    @Autowired
    private RandomValueAuthorizationCodeServices authorizationCodeServices;

    @Autowired
    private TokenGranter tokenGranter;

    /**
     * 第一个方法: 对应于配置AuthorizationServer安全认证的相关信息，创建ClientCredentialsTokenEndpointFilter核心过滤器 设置 /oauth/check_token
     * 端点，通过认证后可访问。
     *
     * @param security
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()")
                //让/oauth/token支持client_id以及client_secret作登录认证
                .allowFormAuthenticationForClients();
    }

    /**
     * 第二个方法: 配置OAuth2的客户端相关信息，客户端认证，是 ClientId 和 ClientSecret 而不是用户账号密码认证 配置应用名称 应用id，这里从 redis 缓存获取
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
        // 初始化的时候，加载所有的 clientid 和 serect，默认 springsecurity 会从表 oauth_client_details 表读取数据
        // 这里做 redis 缓存
        clientDetailsService.loadAllClientToCache();
    }

    /**
     * 第三个方法: 配置身份认证器，配置认证方式，TokenStore，TokenGranter，OAuth2RequestFactory 授权之前要认证，认证方式来自Spring Security 的配置类
     * com.central.oauth.config.SecurityConfig#authenticationManagerBean()
     *
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .authorizationCodeServices(authorizationCodeServices)
                .exceptionTranslator(webResponseExceptionTranslator)
                // 设置授权模式 指向 com.central.oauth.config.TokenGranterConfig.tokenGranter
                // 具体使用什么授权模式，是用户在请求接口的时候指定的 grant_type 参数判断
                .tokenGranter(tokenGranter);
    }

}
